



<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#FFF">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/amatsutsumi.ico">

<link rel="icon" type="image/ico" sizes="32x32" href="/images/favicon.ico">
  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">


<link rel="alternate" type="application/rss+xml" title="auroraの失落之境" href="https://auroraisok.gitee.io/rss.xml" />
<link rel="alternate" type="application/atom+xml" title="auroraの失落之境" href="https://auroraisok.gitee.io/atom.xml" />
<link rel="alternate" type="application/json" title="auroraの失落之境" href="https://auroraisok.gitee.io/feed.json" />

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Mulish:300,300italic,400,400italic,700,700italic%7CFredericka%20the%20Great:300,300italic,400,400italic,700,700italic%7CNoto%20Serif%20JP:300,300italic,400,400italic,700,700italic%7CNoto%20Serif%20SC:300,300italic,400,400italic,700,700italic%7CInconsolata:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/css/app.css?v=0.2.5">

  

<link rel="canonical" href="https://auroraisok.gitee.io/2024/02/28/python/">



  <title>
函数和模块的使用 |
aurora = auroraの失落之境 = 吾は悪事も一言、善事も一言、言い离つ神。</title>
<meta name="generator" content="Hexo 6.3.0"></head>
<body itemscope itemtype="http://schema.org/WebPage">
  <div id="loading">
    <div class="cat">
      <div class="body"></div>
      <div class="head">
        <div class="face"></div>
      </div>
      <div class="foot">
        <div class="tummy-end"></div>
        <div class="bottom"></div>
        <div class="legs left"></div>
        <div class="legs right"></div>
      </div>
      <div class="paw">
        <div class="hands left"></div>
        <div class="hands right"></div>
      </div>
    </div>
  </div>
  <div id="container">
    <header id="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="inner">
        <div id="brand">
          <div class="pjax">
          
  <h1 itemprop="name headline">函数和模块的使用
  </h1>
  
<div class="meta">
  <span class="item" title="创建时间：2024-02-28 10:53:48">
    <span class="icon">
      <i class="ic i-calendar"></i>
    </span>
    <span class="text">发表于</span>
    <time itemprop="dateCreated datePublished" datetime="2024-02-28T10:53:48+08:00">2024-02-28</time>
  </span>
</div>


          </div>
        </div>
        <nav id="nav">
  <div class="inner">
    <div class="toggle">
      <div class="lines" aria-label="切换导航栏">
        <span class="line"></span>
        <span class="line"></span>
        <span class="line"></span>
      </div>
    </div>
    <ul class="menu">
      <li class="item title"><a href="/" rel="start">aurora</a></li>
    </ul>
    <ul class="right">
      <li class="item theme">
        <i class="ic i-sun"></i>
      </li>
      <li class="item search">
        <i class="ic i-search"></i>
      </li>
    </ul>
  </div>
</nav>

      </div>
      <div id="imgs" class="pjax">
        <ul>
          <li class="item" data-background-image="https://img.moehu.org/pic.php?id=img1?719392"></li>
          <li class="item" data-background-image="https://img.moehu.org/pic.php?id=img1?361208"></li>
          <li class="item" data-background-image="https://img.moehu.org/pic.php?id=img1?709736"></li>
          <li class="item" data-background-image="https://img.moehu.org/pic.php?id=img1?512208"></li>
          <li class="item" data-background-image="https://img.moehu.org/pic.php?id=img1?560976"></li>
          <li class="item" data-background-image="https://img.moehu.org/pic.php?id=img1?531914"></li>
        </ul>
      </div>
    </header>
    <div id="waves">
      <svg class="waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
        <defs>
          <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z" />
        </defs>
        <g class="parallax">
          <use xlink:href="#gentle-wave" x="48" y="0" />
          <use xlink:href="#gentle-wave" x="48" y="3" />
          <use xlink:href="#gentle-wave" x="48" y="5" />
          <use xlink:href="#gentle-wave" x="48" y="7" />
        </g>
      </svg>
    </div>
    <main>
      <div class="inner">
        <div id="main" class="pjax">
          
  <div class="article wrap">
    
<div class="breadcrumb" itemscope itemtype="https://schema.org/BreadcrumbList">
<i class="ic i-home"></i>
<span><a href="/">首页</a></span>
</div>

    <article itemscope itemtype="http://schema.org/Article" class="post block" lang="zh-CN">
  <link itemprop="mainEntityOfPage" href="https://auroraisok.gitee.io/2024/02/28/python/">

  <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="image" content="/images/avatar.jpg">
    <meta itemprop="name" content="aurora">
    <meta itemprop="description" content="吾は悪事も一言、善事も一言、言い离つ神。, 水仙，花语是，珍爱自己">
  </span>

  <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="auroraの失落之境">
  </span>

  <div class="body md" itemprop="articleBody">
    

    <p>因为比较难学，专门记载一下。</p>
<h2 id="函数和模块的使用"><a class="markdownIt-Anchor" href="#函数和模块的使用">#</a> 函数和模块的使用</h2>
<p>在讲解本章节的内容之前，我们先来研究一道数学题，请说出下面的方程有多少组正整数解。</p>
<p><img data-src="./res/formula_3.png" alt="$$x_1 + x_2 + x_3 + x_4 = 8$$"></p>
<p>事实上，上面的问题等同于将 8 个苹果分成四组每组至少一个苹果有多少种方案。想到这一点问题的答案就呼之欲出了。</p>
<p><img data-src="./res/formula_4.png" alt="$$C_M^N =\frac{M!}{N!(M-N)!}, \text{(M=7, N=3)} $$"></p>
<p>可以用 Python 的程序来计算出这个值，代码如下所示。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">输入M和N计算C(M,N)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">Version: 0.1</span></span><br><span class="line"><span class="string">Author: 骆昊</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line">m = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&#x27;m = &#x27;</span>))</span><br><span class="line">n = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&#x27;n = &#x27;</span>))</span><br><span class="line">fm = <span class="number">1</span></span><br><span class="line"><span class="keyword">for</span> num <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, m + <span class="number">1</span>):</span><br><span class="line">    fm *= num</span><br><span class="line">fn = <span class="number">1</span></span><br><span class="line"><span class="keyword">for</span> num <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, n + <span class="number">1</span>):</span><br><span class="line">    fn *= num</span><br><span class="line">fm_n = <span class="number">1</span></span><br><span class="line"><span class="keyword">for</span> num <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, m - n + <span class="number">1</span>):</span><br><span class="line">    fm_n *= num</span><br><span class="line"><span class="built_in">print</span>(fm // fn // fm_n)</span><br></pre></td></tr></table></figure>
<h3 id="函数的作用"><a class="markdownIt-Anchor" href="#函数的作用">#</a> 函数的作用</h3>
<p>不知道大家是否注意到，在上面的代码中，我们做了 3 次求阶乘，这样的代码实际上就是重复代码。编程大师<em> Martin Fowler</em> 先生曾经说过：“<strong>代码有很多种坏味道，重复是最坏的一种！</strong>”，要写出高质量的代码首先要解决的就是重复代码的问题。对于上面的代码来说，我们可以将计算阶乘的功能封装到一个称之为 “函数” 的功能模块中，在需要计算阶乘的地方，我们只需要 “调用” 这个 “函数” 就可以了。</p>
<h3 id="定义函数"><a class="markdownIt-Anchor" href="#定义函数">#</a> 定义函数</h3>
<p>在 Python 中可以使用 <code>def</code>  关键字来定义函数，和变量一样每个函数也有一个响亮的名字，而且命名规则跟变量的命名规则是一致的。在函数名后面的圆括号中可以放置传递给函数的参数，这一点和数学上的函数非常相似，程序中函数的参数就相当于是数学上说的函数的自变量，而函数执行完成后我们可以通过 <code>return</code>  关键字来返回一个值，这相当于数学上说的函数的因变量。</p>
<p>在了解了如何定义函数后，我们可以对上面的代码进行重构，所谓重构就是在不影响代码执行结果的前提下对代码的结构进行调整，重构之后的代码如下所示。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">输入M和N计算C(M,N)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">Version: 0.1</span></span><br><span class="line"><span class="string">Author: 骆昊</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">fac</span>(<span class="params">num</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;求阶乘&quot;&quot;&quot;</span></span><br><span class="line">    result = <span class="number">1</span></span><br><span class="line">    <span class="keyword">for</span> n <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, num + <span class="number">1</span>):</span><br><span class="line">        result *= n</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">m = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&#x27;m = &#x27;</span>))</span><br><span class="line">n = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&#x27;n = &#x27;</span>))</span><br><span class="line"><span class="comment"># 当需要计算阶乘的时候不用再写循环求阶乘而是直接调用已经定义好的函数</span></span><br><span class="line"><span class="built_in">print</span>(fac(m) // fac(n) // fac(m - n))</span><br></pre></td></tr></table></figure>
<blockquote>
<p><strong>说明：</strong> Python 的 <code>math</code>  模块中其实已经有一个名为 <code>factorial</code>  函数实现了阶乘运算，事实上求阶乘并不用自己定义函数。下面的例子中，我们讲的函数在 Python 标准库已经实现过了，我们这里是为了讲解函数的定义和使用才把它们又实现了一遍，<strong>实际开发中并不建议做这种低级的重复劳动</strong>。</p>
</blockquote>
<h3 id="函数的参数"><a class="markdownIt-Anchor" href="#函数的参数">#</a> 函数的参数</h3>
<p>函数是绝大多数编程语言中都支持的一个代码的 &quot;构建块&quot;，但是 Python 中的函数与其他语言中的函数还是有很多不太相同的地方，其中一个显著的区别就是 Python 对函数参数的处理。在 Python 中，函数的参数可以有默认值，也支持使用可变参数，所以 Python 并不需要像其他语言一样支持<span class="exturl" data-url="aHR0cHM6Ly96aC53aWtpcGVkaWEub3JnL3dpa2kvJUU1JTg3JUJEJUU2JTk1JUIwJUU5JTg3JThEJUU4JUJEJUJE">函数的重载</span>，因为我们在定义一个函数的时候可以让它有多种不同的使用方式，下面是两个小例子。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> random <span class="keyword">import</span> randint</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">roll_dice</span>(<span class="params">n=<span class="number">2</span></span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;摇色子&quot;&quot;&quot;</span></span><br><span class="line">    total = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">        total += randint(<span class="number">1</span>, <span class="number">6</span>)</span><br><span class="line">    <span class="keyword">return</span> total</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">add</span>(<span class="params">a=<span class="number">0</span>, b=<span class="number">0</span>, c=<span class="number">0</span></span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;三个数相加&quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">return</span> a + b + c</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果没有指定参数那么使用默认值摇两颗色子</span></span><br><span class="line"><span class="built_in">print</span>(roll_dice())</span><br><span class="line"><span class="comment"># 摇三颗色子</span></span><br><span class="line"><span class="built_in">print</span>(roll_dice(<span class="number">3</span>))</span><br><span class="line"><span class="built_in">print</span>(add())</span><br><span class="line"><span class="built_in">print</span>(add(<span class="number">1</span>))</span><br><span class="line"><span class="built_in">print</span>(add(<span class="number">1</span>, <span class="number">2</span>))</span><br><span class="line"><span class="built_in">print</span>(add(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>))</span><br><span class="line"><span class="comment"># 传递参数时可以不按照设定的顺序进行传递</span></span><br><span class="line"><span class="built_in">print</span>(add(c=<span class="number">50</span>, a=<span class="number">100</span>, b=<span class="number">200</span>))</span><br></pre></td></tr></table></figure>
<p>我们给上面两个函数的参数都设定了默认值，这也就意味着如果在调用函数的时候如果没有传入对应参数的值时将使用该参数的默认值，所以在上面的代码中我们可以用各种不同的方式去调用 <code>add</code>  函数，这跟其他很多语言中函数重载的效果是一致的。</p>
<p>其实上面的 <code>add</code>  函数还有更好的实现方案，因为我们可能会对 0 个或多个参数进行加法运算，而具体有多少个参数是由调用者来决定，我们作为函数的设计者对这一点是一无所知的，因此在不确定参数个数的时候，我们可以使用可变参数，代码如下所示。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 在参数名前面的*表示args是一个可变参数</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">add</span>(<span class="params">*args</span>):</span><br><span class="line">    total = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> val <span class="keyword">in</span> args:</span><br><span class="line">        total += val</span><br><span class="line">    <span class="keyword">return</span> total</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 在调用add函数时可以传入0个或多个参数</span></span><br><span class="line"><span class="built_in">print</span>(add())</span><br><span class="line"><span class="built_in">print</span>(add(<span class="number">1</span>))</span><br><span class="line"><span class="built_in">print</span>(add(<span class="number">1</span>, <span class="number">2</span>))</span><br><span class="line"><span class="built_in">print</span>(add(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>))</span><br><span class="line"><span class="built_in">print</span>(add(<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>))</span><br></pre></td></tr></table></figure>
<h3 id="用模块管理函数"><a class="markdownIt-Anchor" href="#用模块管理函数">#</a> 用模块管理函数</h3>
<p>对于任何一种编程语言来说，给变量、函数这样的标识符起名字都是一个让人头疼的问题，因为我们会遇到命名冲突这种尴尬的情况。最简单的场景就是在同一个.py 文件中定义了两个同名函数，由于 Python 没有函数重载的概念，那么后面的定义会覆盖之前的定义，也就意味着两个函数同名函数实际上只有一个是存在的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">foo</span>():</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;hello, world!&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">foo</span>():</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;goodbye, world!&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 下面的代码会输出什么呢？</span></span><br><span class="line">foo()</span><br></pre></td></tr></table></figure>
<p>当然上面的这种情况我们很容易就能避免，但是如果项目是由多人协作进行团队开发的时候，团队中可能有多个程序员都定义了名为 <code>foo</code>  的函数，那么怎么解决这种命名冲突呢？答案其实很简单，Python 中每个文件就代表了一个模块（module），我们在不同的模块中可以有同名的函数，在使用函数的时候我们通过 <code>import</code>  关键字导入指定的模块就可以区分到底要使用的是哪个模块中的 <code>foo</code>  函数，代码如下所示。</p>
<p><code>module1.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">foo</span>():</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;hello, world!&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p><code>module2.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">foo</span>():</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;goodbye, world!&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p><code>test.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> module1 <span class="keyword">import</span> foo</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出hello, world!</span></span><br><span class="line">foo()</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> module2 <span class="keyword">import</span> foo</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出goodbye, world!</span></span><br><span class="line">foo()</span><br></pre></td></tr></table></figure>
<p>也可以按照如下所示的方式来区分到底要使用哪一个 <code>foo</code>  函数。</p>
<p><code>test.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> module1 <span class="keyword">as</span> m1</span><br><span class="line"><span class="keyword">import</span> module2 <span class="keyword">as</span> m2</span><br><span class="line"></span><br><span class="line">m1.foo()</span><br><span class="line">m2.foo()</span><br></pre></td></tr></table></figure>
<p>但是如果将代码写成了下面的样子，那么程序中调用的是最后导入的那个 <code>foo</code> ，因为后导入的 foo 覆盖了之前导入的 <code>foo</code> 。</p>
<p><code>test.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> module1 <span class="keyword">import</span> foo</span><br><span class="line"><span class="keyword">from</span> module2 <span class="keyword">import</span> foo</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出goodbye, world!</span></span><br><span class="line">foo()</span><br></pre></td></tr></table></figure>
<p><code>test.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> module2 <span class="keyword">import</span> foo</span><br><span class="line"><span class="keyword">from</span> module1 <span class="keyword">import</span> foo</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出hello, world!</span></span><br><span class="line">foo()</span><br></pre></td></tr></table></figure>
<p>需要说明的是，如果我们导入的模块除了定义函数之外还有可以执行代码，那么 Python 解释器在导入这个模块时就会执行这些代码，事实上我们可能并不希望如此，因此如果我们在模块中编写了执行代码，最好是将这些执行代码放入如下所示的条件中，这样的话除非直接运行该模块，if 条件下的这些代码是不会执行的，因为只有直接执行的模块的名字才是 &quot;__main__&quot;。</p>
<p><code>module3.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">foo</span>():</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">bar</span>():</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># __name__是Python中一个隐含的变量它代表了模块的名字</span></span><br><span class="line"><span class="comment"># 只有被Python解释器直接执行的模块的名字才是__main__</span></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;call foo()&#x27;</span>)</span><br><span class="line">    foo()</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;call bar()&#x27;</span>)</span><br><span class="line">    bar()</span><br></pre></td></tr></table></figure>
<p><code>test.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> module3</span><br><span class="line"></span><br><span class="line"><span class="comment"># 导入module3时 不会执行模块中if条件成立时的代码 因为模块的名字是module3而不是__main__</span></span><br></pre></td></tr></table></figure>
<h3 id="练习"><a class="markdownIt-Anchor" href="#练习">#</a> 练习</h3>
<h4 id="练习1实现计算求最大公约数和最小公倍数的函数"><a class="markdownIt-Anchor" href="#练习1实现计算求最大公约数和最小公倍数的函数">#</a> 练习 1：实现计算求最大公约数和最小公倍数的函数。</h4>
<p>参考答案：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">gcd</span>(<span class="params">x, y</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;求最大公约数&quot;&quot;&quot;</span></span><br><span class="line">    (x, y) = (y, x) <span class="keyword">if</span> x &gt; y <span class="keyword">else</span> (x, y)</span><br><span class="line">    <span class="keyword">for</span> factor <span class="keyword">in</span> <span class="built_in">range</span>(x, <span class="number">0</span>, -<span class="number">1</span>):</span><br><span class="line">        <span class="keyword">if</span> x % factor == <span class="number">0</span> <span class="keyword">and</span> y % factor == <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">return</span> factor</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">lcm</span>(<span class="params">x, y</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;求最小公倍数&quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">return</span> x * y // gcd(x, y)</span><br></pre></td></tr></table></figure>
<h4 id="练习2实现判断一个数是不是回文数的函数"><a class="markdownIt-Anchor" href="#练习2实现判断一个数是不是回文数的函数">#</a> 练习 2：实现判断一个数是不是回文数的函数。</h4>
<p>参考答案：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">is_palindrome</span>(<span class="params">num</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;判断一个数是不是回文数&quot;&quot;&quot;</span></span><br><span class="line">    temp = num</span><br><span class="line">    total = <span class="number">0</span></span><br><span class="line">    <span class="keyword">while</span> temp &gt; <span class="number">0</span>:</span><br><span class="line">        total = total * <span class="number">10</span> + temp % <span class="number">10</span></span><br><span class="line">        temp //= <span class="number">10</span></span><br><span class="line">    <span class="keyword">return</span> total == num</span><br></pre></td></tr></table></figure>
<h4 id="练习3实现判断一个数是不是素数的函数"><a class="markdownIt-Anchor" href="#练习3实现判断一个数是不是素数的函数">#</a> 练习 3：实现判断一个数是不是素数的函数。</h4>
<p>参考答案：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">is_prime</span>(<span class="params">num</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;判断一个数是不是素数&quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">for</span> factor <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">2</span>, <span class="built_in">int</span>(num ** <span class="number">0.5</span>) + <span class="number">1</span>):</span><br><span class="line">        <span class="keyword">if</span> num % factor == <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">True</span> <span class="keyword">if</span> num != <span class="number">1</span> <span class="keyword">else</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure>
<h4 id="练习4写一个程序判断输入的正整数是不是回文素数"><a class="markdownIt-Anchor" href="#练习4写一个程序判断输入的正整数是不是回文素数">#</a> 练习 4：写一个程序判断输入的正整数是不是回文素数。</h4>
<p>参考答案：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    num = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&#x27;请输入正整数: &#x27;</span>))</span><br><span class="line">    <span class="keyword">if</span> is_palindrome(num) <span class="keyword">and</span> is_prime(num):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;%d是回文素数&#x27;</span> % num)</span><br></pre></td></tr></table></figure>
<blockquote>
<p><strong>注意</strong>：通过上面的程序可以看出，当我们<strong>将代码中重复出现的和相对独立的功能抽取成函数</strong>后，我们可以<strong>组合使用这些函数</strong>来解决更为复杂的问题，这也是我们为什么要定义和使用函数的一个非常重要的原因。</p>
</blockquote>
<h3 id="变量的作用域"><a class="markdownIt-Anchor" href="#变量的作用域">#</a> 变量的作用域</h3>
<p>最后，我们来讨论一下 Python 中有关变量作用域的问题。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">foo</span>():</span><br><span class="line">    b = <span class="string">&#x27;hello&#x27;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># Python中可以在函数内部再定义函数</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">bar</span>():</span><br><span class="line">        c = <span class="literal">True</span></span><br><span class="line">        <span class="built_in">print</span>(a)</span><br><span class="line">        <span class="built_in">print</span>(b)</span><br><span class="line">        <span class="built_in">print</span>(c)</span><br><span class="line"></span><br><span class="line">    bar()</span><br><span class="line">    <span class="comment"># print(c)  # NameError: name &#x27;c&#x27; is not defined</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    a = <span class="number">100</span></span><br><span class="line">    <span class="comment"># print(b)  # NameError: name &#x27;b&#x27; is not defined</span></span><br><span class="line">    foo()</span><br></pre></td></tr></table></figure>
<p>上面的代码能够顺利的执行并且打印出 100、hello 和 True，但我们注意到了，在 <code>bar</code>  函数的内部并没有定义 <code>a</code>  和 <code>b</code>  两个变量，那么 <code>a</code>  和 <code>b</code>  是从哪里来的。我们在上面代码的 <code>if</code>  分支中定义了一个变量 <code>a</code> ，这是一个全局变量（global variable），属于全局作用域，因为它没有定义在任何一个函数中。在上面的 <code>foo</code>  函数中我们定义了变量 <code>b</code> ，这是一个定义在函数中的局部变量（local variable），属于局部作用域，在 <code>foo</code>  函数的外部并不能访问到它；但对于 <code>foo</code>  函数内部的 <code>bar</code>  函数来说，变量 <code>b</code>  属于嵌套作用域，在 <code>bar</code>  函数中我们是可以访问到它的。 <code>bar</code>  函数中的变量 <code>c</code>  属于局部作用域，在 <code>bar</code>  函数之外是无法访问的。事实上，Python 查找一个变量时会按照 “局部作用域”、“嵌套作用域”、“全局作用域” 和 “内置作用域” 的顺序进行搜索，前三者我们在上面的代码中已经看到了，所谓的 “内置作用域” 就是 Python 内置的那些标识符，我们之前用过的 <code>input</code> 、 <code>print</code> 、 <code>int</code>  等都属于内置作用域。</p>
<p>再看看下面这段代码，我们希望通过函数调用修改全局变量 <code>a</code>  的值，但实际上下面的代码是做不到的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">foo</span>():</span><br><span class="line">    a = <span class="number">200</span></span><br><span class="line">    <span class="built_in">print</span>(a)  <span class="comment"># 200</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    a = <span class="number">100</span></span><br><span class="line">    foo()</span><br><span class="line">    <span class="built_in">print</span>(a)  <span class="comment"># 100</span></span><br></pre></td></tr></table></figure>
<p>在调用 <code>foo</code>  函数后，我们发现 <code>a</code>  的值仍然是 100，这是因为当我们在函数 <code>foo</code>  中写 <code>a = 200</code>  的时候，是重新定义了一个名字为 <code>a</code>  的局部变量，它跟全局作用域的 <code>a</code>  并不是同一个变量，因为局部作用域中有了自己的变量 <code>a</code> ，因此 <code>foo</code>  函数不再搜索全局作用域中的 <code>a</code> 。如果我们希望在 <code>foo</code>  函数中修改全局作用域中的 <code>a</code> ，代码如下所示。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">foo</span>():</span><br><span class="line">    <span class="keyword">global</span> a</span><br><span class="line">    a = <span class="number">200</span></span><br><span class="line">    <span class="built_in">print</span>(a)  <span class="comment"># 200</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    a = <span class="number">100</span></span><br><span class="line">    foo()</span><br><span class="line">    <span class="built_in">print</span>(a)  <span class="comment"># 200</span></span><br></pre></td></tr></table></figure>
<p>我们可以使用 <code>global</code>  关键字来指示 <code>foo</code>  函数中的变量 <code>a</code>  来自于全局作用域，如果全局作用域中没有 <code>a</code> ，那么下面一行的代码就会定义变量 <code>a</code>  并将其置于全局作用域。同理，如果我们希望函数内部的函数能够修改嵌套作用域中的变量，可以使用 <code>nonlocal</code>  关键字来指示变量来自于嵌套作用域，请大家自行试验。</p>
<p>在实际开发中，我们应该尽量减少对全局变量的使用，因为全局变量的作用域和影响过于广泛，可能会发生意料之外的修改和使用，除此之外全局变量比局部变量拥有更长的生命周期，可能导致对象占用的内存长时间无法被<span class="exturl" data-url="aHR0cHM6Ly96aC53aWtpcGVkaWEub3JnL3dpa2kvJUU1JTlFJTgzJUU1JTlDJUJFJUU1JTlCJTlFJUU2JTk0JUI2XyglRTglQTglODglRTclQUUlOTclRTYlQTklOUYlRTclQTclOTElRTUlQUQlQjgp">垃圾回收</span>。事实上，减少对全局变量的使用，也是降低代码之间耦合度的一个重要举措，同时也是对<span class="exturl" data-url="aHR0cHM6Ly96aC53aWtpcGVkaWEub3JnL3poLWhhbnMvJUU1JUJFJTk3JUU1JUEyJUE4JUU1JUJGJTkyJUU4JTgwJUIzJUU1JUFFJTlBJUU1JUJFJThC">迪米特法则</span>的践行。减少全局变量的使用就意味着我们应该尽量让变量的作用域在函数的内部，但是如果我们希望将一个局部变量的生命周期延长，使其在定义它的函数调用结束后依然可以使用它的值，这时候就需要使用<span class="exturl" data-url="aHR0cHM6Ly96aC53aWtpcGVkaWEub3JnL3dpa2kvJUU5JTk3JUFEJUU1JThDJTg1XyglRTglQUUlQTElRTclQUUlOTclRTYlOUMlQkElRTclQTclOTElRTUlQUQlQTYp">闭包</span>，这个我们在后续的内容中进行讲解。</p>
<blockquote>
<p><strong>说明：</strong> 很多人经常会将 “闭包” 和<span class="exturl" data-url="aHR0cHM6Ly96aC53aWtpcGVkaWEub3JnL3dpa2kvJUU1JThDJUJGJUU1JTkwJThEJUU1JTg3JUJEJUU2JTk1JUIw"> “匿名函数”</span> 混为一谈，但实际上它们并不是一回事，如果想了解这个概念，可以看看<span class="exturl" data-url="aHR0cHM6Ly96aC53aWtpcGVkaWEub3JnL3dpa2kv">维基百科</span>的解释或者<span class="exturl" data-url="aHR0cHM6Ly93d3cuemhpaHUuY29tLw==">知乎</span>上对这个概念的讨论。</p>
</blockquote>
<p>说了那么多，其实结论很简单，从现在开始我们可以将 Python 代码按照下面的格式进行书写，这一点点的改进其实就是在我们理解了函数和作用域的基础上跨出的巨大的一步。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">main</span>():</span><br><span class="line">    <span class="comment"># Todo: Add your code here</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

  </div>

   <footer>

    <div class="meta">
  <span class="item">
    <span class="icon">
      <i class="ic i-calendar-check"></i>
    </span>
    <span class="text">更新于</span>
    <time title="修改时间：2024-02-28 10:55:30" itemprop="dateModified" datetime="2024-02-28T10:55:30+08:00">2024-02-28</time>
  </span>
  <span id="2024/02/28/python/" class="item leancloud_visitors" data-flag-title="函数和模块的使用" title="阅读次数">
      <span class="icon">
        <i class="ic i-eye"></i>
      </span>
      <span class="text">阅读次数</span>
      <span class="leancloud-visitors-count"></span>
      <span class="text">次</span>
  </span>
</div>

      
<div class="reward">
  <button><i class="ic i-heartbeat"></i> 赞赏</button>
  <p>请我喝[茶]~(￣▽￣)~*</p>
  <div id="qr">
      
      <div>
        <img data-src="/images/wechatpay.png" alt="aurora 微信支付">
        <p>微信支付</p>
      </div>
      
      <div>
        <img data-src="/images/alipay.png" alt="aurora 支付宝">
        <p>支付宝</p>
      </div>
      
      <div>
        <img data-src="/images/paypal.png" alt="aurora 贝宝">
        <p>贝宝</p>
      </div>
  </div>
</div>

      

<div id="copyright">
<ul>
  <li class="author">
    <strong>本文作者： </strong>aurora <i class="ic i-at"><em>@</em></i>auroraの失落之境
  </li>
  <li class="link">
    <strong>本文链接：</strong>
    <a href="https://auroraisok.gitee.io/2024/02/28/python/" title="函数和模块的使用">https://auroraisok.gitee.io/2024/02/28/python/</a>
  </li>
  <li class="license">
    <strong>版权声明： </strong>本站所有文章除特别声明外，均采用 <span class="exturl" data-url="aHR0cHM6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL2J5LW5jLXNhLzQuMC9kZWVkLnpo"><i class="ic i-creative-commons"><em>(CC)</em></i>BY-NC-SA</span> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

  </footer>

</article>

  </div>
  

<div class="post-nav">
    <div class="item left">
      

  <a href="/2024/02/27/%E6%84%9F%E8%A7%89-%E5%8F%AF%E8%83%BD%E8%A6%81%E7%95%99%E7%BA%A7%E4%BA%86/" itemprop="url" rel="prev" data-background-image="https:&#x2F;&#x2F;img.moehu.org&#x2F;pic.php?id&#x3D;img1?960413" title="感觉...可能要留级了">
  <span class="type">上一篇</span>
  <span class="category"><i class="ic i-flag"></i> </span>
  <h3>感觉...可能要留级了</h3>
  </a>

    </div>
    <div class="item right">
      

  <a href="/2024/02/29/python%E7%AC%AC%E4%B8%83%E5%A4%A9/" itemprop="url" rel="next" data-background-image="https:&#x2F;&#x2F;img.moehu.org&#x2F;pic.php?id&#x3D;img1?984502" title="1">
  <span class="type">下一篇</span>
  <span class="category"><i class="ic i-flag"></i> </span>
  <h3>1</h3>
  </a>

    </div>
</div>

  
  <div class="wrap" id="comments"></div>


        </div>
        <div id="sidebar">
          

<div class="inner">

  <div class="panels">
    <div class="inner">
      <div class="contents panel pjax" data-title="文章目录">
          <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E5%92%8C%E6%A8%A1%E5%9D%97%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-number">1.</span> <span class="toc-text"> 函数和模块的使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E7%9A%84%E4%BD%9C%E7%94%A8"><span class="toc-number">1.1.</span> <span class="toc-text"> 函数的作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E5%87%BD%E6%95%B0"><span class="toc-number">1.2.</span> <span class="toc-text"> 定义函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E7%9A%84%E5%8F%82%E6%95%B0"><span class="toc-number">1.3.</span> <span class="toc-text"> 函数的参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%A8%E6%A8%A1%E5%9D%97%E7%AE%A1%E7%90%86%E5%87%BD%E6%95%B0"><span class="toc-number">1.4.</span> <span class="toc-text"> 用模块管理函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%83%E4%B9%A0"><span class="toc-number">1.5.</span> <span class="toc-text"> 练习</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%83%E4%B9%A01%E5%AE%9E%E7%8E%B0%E8%AE%A1%E7%AE%97%E6%B1%82%E6%9C%80%E5%A4%A7%E5%85%AC%E7%BA%A6%E6%95%B0%E5%92%8C%E6%9C%80%E5%B0%8F%E5%85%AC%E5%80%8D%E6%95%B0%E7%9A%84%E5%87%BD%E6%95%B0"><span class="toc-number">1.5.1.</span> <span class="toc-text"> 练习 1：实现计算求最大公约数和最小公倍数的函数。</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%83%E4%B9%A02%E5%AE%9E%E7%8E%B0%E5%88%A4%E6%96%AD%E4%B8%80%E4%B8%AA%E6%95%B0%E6%98%AF%E4%B8%8D%E6%98%AF%E5%9B%9E%E6%96%87%E6%95%B0%E7%9A%84%E5%87%BD%E6%95%B0"><span class="toc-number">1.5.2.</span> <span class="toc-text"> 练习 2：实现判断一个数是不是回文数的函数。</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%83%E4%B9%A03%E5%AE%9E%E7%8E%B0%E5%88%A4%E6%96%AD%E4%B8%80%E4%B8%AA%E6%95%B0%E6%98%AF%E4%B8%8D%E6%98%AF%E7%B4%A0%E6%95%B0%E7%9A%84%E5%87%BD%E6%95%B0"><span class="toc-number">1.5.3.</span> <span class="toc-text"> 练习 3：实现判断一个数是不是素数的函数。</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%83%E4%B9%A04%E5%86%99%E4%B8%80%E4%B8%AA%E7%A8%8B%E5%BA%8F%E5%88%A4%E6%96%AD%E8%BE%93%E5%85%A5%E7%9A%84%E6%AD%A3%E6%95%B4%E6%95%B0%E6%98%AF%E4%B8%8D%E6%98%AF%E5%9B%9E%E6%96%87%E7%B4%A0%E6%95%B0"><span class="toc-number">1.5.4.</span> <span class="toc-text"> 练习 4：写一个程序判断输入的正整数是不是回文素数。</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E7%9A%84%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-number">1.6.</span> <span class="toc-text"> 变量的作用域</span></a></li></ol></li></ol>
      </div>
      <div class="related panel pjax" data-title="系列文章">
      </div>
      <div class="overview panel" data-title="站点概览">
        <div class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <img class="image" itemprop="image" alt="aurora"
      data-src="/images/avatar.jpg">
  <p class="name" itemprop="name">aurora</p>
  <div class="description" itemprop="description">水仙，花语是，珍爱自己</div>
</div>

<nav class="state">
    <div class="item posts">
      <a href="/archives/">
        <span class="count">71</span>
        <span class="name">文章</span>
      </a>
    </div>
    <div class="item tags">
      <a href="/tags/">
        <span class="count">8</span>
        <span class="name">标签</span>
      </a>
    </div>
</nav>

<div class="social">
</div>

<ul class="menu">
  
    
  <li class="item">
    <a href="/" rel="section"><i class="ic i-home"></i>首页</a>
  </li>

    
  <li class="item">
    <a href="/about/" rel="section"><i class="ic i-user"></i>关于</a>
  </li>

        
  <li class="item dropdown">
      <a href="javascript:void(0);"><i class="ic i-feather"></i>文章</a>
    <ul class="submenu">

        
  <li class="item">
    <a href="/archives/" rel="section"><i class="ic i-list-alt"></i>归档</a>
  </li>

        
  <li class="item">
    <a href="/categories/" rel="section"><i class="ic i-th"></i>分类</a>
  </li>

        
  <li class="item">
    <a href="/tags/" rel="section"><i class="ic i-tags"></i>标签</a>
  </li>

  </ul>
    
  <li class="item">
    <a href="/friends/" rel="section"><i class="ic i-user-secret"></i>Q群和友链</a>
  </li>

    
  <li class="item">
    <a href="/liuyan/" rel="section"><i class="ic i-feather"></i>留言板</a>
  </li>

    
  <li class="item">
    <a href="/liaotian/" rel="section"><i class="ic i-feather"></i>在线聊天室</a>
  </li>


</ul>

      </div>
    </div>
  </div>

  <ul id="quick">
    <li class="prev pjax">
        <a href="/2024/02/27/%E6%84%9F%E8%A7%89-%E5%8F%AF%E8%83%BD%E8%A6%81%E7%95%99%E7%BA%A7%E4%BA%86/" rel="prev" title="上一篇"><i class="ic i-chevron-left"></i></a>
    </li>
    <li class="up"><i class="ic i-arrow-up"></i></li>
    <li class="down"><i class="ic i-arrow-down"></i></li>
    <li class="next pjax">
        <a href="/2024/02/29/python%E7%AC%AC%E4%B8%83%E5%A4%A9/" rel="next" title="下一篇"><i class="ic i-chevron-right"></i></a>
    </li>
    <li class="percent"></li>
  </ul>
</div>


        </div>
        <div class="dimmer"></div>
      </div>
    </main>
    <footer id="footer">
      <div class="inner">
        <div class="widgets">
          
<div class="rpost pjax">
  <h2>随机文章</h2>
  <ul>
      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/2024/02/12/%E9%AD%94%E6%B3%95%E5%88%86%E4%BA%AB/" title="魔法分享">魔法分享</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/2024/02/17/%E3%80%90%E8%B5%84%E6%BA%90%E7%BD%91%E7%AB%99%E6%8E%A8%E8%8D%90%E3%80%91%E5%B8%AE%E9%9A%94%E5%A3%81%E5%AE%A3%E7%AB%99/" title="【资源网站推荐】帮隔壁宣站">【资源网站推荐】帮隔壁宣站</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/2024/03/17/%E5%8F%82%E4%B8%8Egal%E5%BC%80%E5%8F%91%E5%B7%A5%E4%BD%9C/" title="参与gal开发工作">参与gal开发工作</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/2024/04/08/%E3%80%90%E6%9D%82%E8%B0%88%E5%90%91%E3%80%91%E6%9C%80%E5%96%9C%E6%AC%A2%E7%9A%84%E5%87%A0%E9%83%A8galgame/" title="【杂谈向】最喜欢的几部galgame">【杂谈向】最喜欢的几部galgame</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/2024/04/26/%E3%80%90%E9%97%B2%E8%81%8A%E5%90%91%E3%80%91%E4%BA%BA%E6%83%85%E4%B8%96%E6%95%85%E3%80%81%E4%B8%BA%E4%BA%BA%E5%A4%84%E4%B8%96/" title="【闲聊向】人情世故、为人处世">【闲聊向】人情世故、为人处世</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/2024/01/27/%E3%80%90%E5%B0%8F%E6%B5%8B%E8%AF%95%E3%80%91%E5%85%A8%E5%9B%BD%E6%9F%9A%E5%AD%90%E5%8E%A8%E9%80%89%E6%8B%94%E8%80%83%E8%AF%95/" title="【小测试】全国柚子厨选拔考试">【小测试】全国柚子厨选拔考试</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/2024/04/15/%E5%9B%9B%E6%9C%88%E5%B0%8F%E8%AE%B0/" title="四月小记">四月小记</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/2023/12/17/aurora%E7%9A%84%E4%B8%A4%E4%B8%AA%E4%B8%AA%E4%BA%BA%E4%B8%BB%E9%A1%B5%E6%BA%90%E7%A0%81%E5%88%86%E4%BA%AB/" title="aurora的两个个人主页源码分享">aurora的两个个人主页源码分享</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/2024/01/24/%E3%80%901000-TB%E3%80%91Alist%E7%BD%91%E7%9B%98/" title="【1000+TB】Alist网盘">【1000+TB】Alist网盘</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/2024/02/13/%E9%9B%B6%E6%88%90%E6%9C%AC%E5%BB%BA%E7%AB%99%EF%BC%9A%E5%85%8D%E8%B4%B9%E6%90%AD%E5%BB%BA%E4%B8%80%E4%B8%AA%E8%87%AA%E5%B7%B1%E7%9A%84%E7%BD%91%E7%AB%99%EF%BC%88%E4%B8%80%EF%BC%89/" title="零成本建站：免费搭建一个自己的网站(一)">零成本建站：免费搭建一个自己的网站(一)</a></span>
  </li>

  </ul>
</div>
<div>
  <h2>最新评论</h2>
  <ul class="leancloud-recent-comment"></ul>
</div>

        </div>
        <div class="status">
  <div class="copyright">
    
    &copy; 2010 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="ic i-sakura rotate"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">aurora @ aurora</span>
  </div>
  <div class="powered-by">
    基于 <span class="exturl" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & Theme.<span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2FtZWhpbWUvaGV4by10aGVtZS1zaG9rYQ==">Shoka</span>
  </div>
</div>

      </div>
    </footer>
  </div>
<script data-config type="text/javascript">
  var LOCAL = {
    path: '2024/02/28/python/',
    favicon: {
      show: "（●´3｀●）やれやれだぜ",
      hide: "(´Д｀)大変だ！"
    },
    search : {
      placeholder: "文章搜索",
      empty: "关于 「 ${query} 」，什么也没搜到",
      stats: "${time} ms 内找到 ${hits} 条结果"
    },
    valine: true,fancybox: true,
    copyright: '复制成功，转载请遵守 <i class="ic i-creative-commons"></i>BY-NC-SA 协议。',
    ignores : [
      function(uri) {
        return uri.includes('#');
      },
      function(uri) {
        return new RegExp(LOCAL.path+"$").test(uri);
      }
    ]
  };
</script>

<script src="https://cdn.polyfill.io/v2/polyfill.js"></script>

<script src="//cdn.jsdelivr.net/combine/npm/pace-js@1.0.2/pace.min.js,npm/pjax@0.2.8/pjax.min.js,npm/whatwg-fetch@3.4.0/dist/fetch.umd.min.js,npm/animejs@3.2.0/lib/anime.min.js,npm/algoliasearch@4/dist/algoliasearch-lite.umd.js,npm/instantsearch.js@4/dist/instantsearch.production.min.js,npm/lozad@1/dist/lozad.min.js,npm/quicklink@2/dist/quicklink.umd.js"></script>

<script src="/js/app.js?v=0.2.5"></script>




<script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>